package com.hongxin.nw.netty.config;

import com.hongxin.nw.netty.utils.pools.ChannelPools;
import com.hongxin.nw.netty.utils.pools.CodePools;
import com.hongxin.nw.netty.utils.pools.HeartBeatPools;
import com.hongxin.nw.netty.values.StaticValue;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Slf4j
@Component
@Configuration
@EnableScheduling
public class SaticScheduleTask {

    //3.添加定时任务
    //@Scheduled(cron = "0/5 * * * * ?")
    //或直接指定时间间隔，例如：5秒
    @Scheduled(fixedRate=5000)
    private void configureTasks() {
        Set<String> strings = HeartBeatPools.getSets();
        if (strings.size() > 0){
            for (String cid : strings) {
                try {
                    long currentTime = System.currentTimeMillis()/1000;
                    long preTime = HeartBeatPools.getHB(cid);
                    long sTime = currentTime - preTime;
//                    log.info("***** 当前时间:{}", currentTime);
//                    log.info("***** 上次时间:{}", preTime);
//                    log.info("***** 差时间:{}", sTime);
                    if (sTime > StaticValue.hbTime){//当前时间大于心跳时间15秒,,则认为设备断开了
                        String code = CodePools.getCode(cid);
                        ChannelHandlerContext ctx = ChannelPools.getCtx(code);
                        ctx.channel().close();
                    }
                }catch (Exception e){
                    log.info("************************************************************");
                    log.info("***** 扫描设备出现异常 {}", e.getMessage());
                    log.info("************************************************************");
                }
            }
        }

    }
}